/*
 * @Author: Jahaw 
 * @Date: 2024-01-29 17:33:01 
 * @Last Modified by: Jahaw
 * @Last Modified time: 2024-01-29 17:44:09
 */
const path = require('path');
const git = require('simple-git');
const { exec } = require('child_process');
const chokidar = require('chokidar');

const repoPath = path.resolve(__dirname, '../');
const branch = 'dev';
const gitWatch = git(repoPath);

// 子仓库路径数组
const subRepos = ['com-sharing', 'webapp-design', 'webapp-runtime', 'webapp-pdf-viewer'];

// 检查，拉取，构建
const pullAndBuild = (subRepo) => {
  console.log(`Checking branch ${branch}`);
  gitWatch.checkout(branch)
  .pull((err) => {
    if (err) console.log('Error pulling:', err);
    else console.log('Pulled updates from', branch);
    exec(`npm --prefix ${subRepo} install ${subRepo} && npm --prefix ${subRepo} run build`,
      (err, stdout, stderr) => {
        if(err) console.log('Error building:', err);
        else console.log(`Build complete for ${subRepo}`);
      });
   });
};

subRepos.forEach(subRepo => {
  const watcher = chokidar.watch(path.join(repoPath, subRepo), { persistent: true });
  watcher.on('ready', () => {
    pullAndBuild(subRepo); // 检查并构建
    watcher.on('change', () => pullAndBuild(subRepo)); // 监听变更
  });
});

